<?php

namespace app\api\service;

use app\api\model\store\Specs as SpecsModel;
use app\api\model\store\SpecsValue as SpecsValueModel;

class SpecsValue extends BaseService
{
    public $model = NULL;
    public $mSpecsValueModel = NULL;

    public function __construct()
    {
        $this->model = new SpecsValueModel();
        $this->mSpecsValueModel = new SpecsValueModel();
    }
    public function dealGoodsSkus($gids, $flagValue) {

        //$specsValueKeys = array_keys($gids);
        $specsValueKeys = array_values($gids);
        foreach($specsValueKeys as $specsValueKey) {
            $specsValueKey = explode(",", $specsValueKey);
            foreach($specsValueKey as $k => $v) {
                $new[$k][] = $v;
                $specsValueIds[] = $v;
            }
        }
        $specsValueIds = array_unique($specsValueIds);
        $specsValues = $this->getNormalInIds($specsValueIds);
        $flagValue = explode(",", $flagValue);
        $result = [];
        foreach($new as $key => $newValue) {
            $newValue = array_unique($newValue);
            $list = [];
            foreach($newValue as $vv) {
                $list[] = [
                    "id" => $vv,
                    "name" => $specsValues[$vv]['name'],
                    "flag" => in_array($vv, $flagValue) ? 1 : 0,
                ];
            }

            $result[$key]  =  [
                "name" => $specsValues[$newValue[0]]['specs_name'],
                "list" => $list,
            ];

        }
        return $result;

    }

    public function getNormalInIds($ids) {
        if(!$ids) {
            return [];
        }

        try {
            $result = $this->model->getNormalInIds($ids);
        }catch (\Exception $e) {
            return [];
        }
        $result = $result->toArray();
        if(!$result) {
            return [];
        }

        /*$specsNames = [
            ["id" => 1, "name" => "颜色"],
            ["id" => 2, "name" => "尺码"],
            ["id" => 3, "name" => "内存"],
            ["id" => 4, "name" => "尺寸"],
            ["id" => 5, "name" => "大小型号"],
        ];*/
        $specsNames = $this->mSpecsValueModel->field('id,name')->where('status', 1)->select();
        if(!$specsNames){
            return [];
        }
        $specsNames = $specsNames->toArray();
        $specsNamesArrs = array_column($specsNames, "name", "id");

        $res = [];
        foreach ($result as $resultValue) {
            $res[$resultValue['id']] = [
                'name' => $resultValue['name'],
                'specs_name' => $specsNamesArrs[$resultValue['specs_id']] ?? "",
            ];
        }

        return $res;

    }

}